package start

import (
	"fmt"
	"time"

	"gitee.com/zatto/project/tree/master/vblog/api/apps"
	"gitee.com/zatto/project/tree/master/vblog/api/conf"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

var (
	configType string
	filePath   string
)

var Cmd = &cobra.Command{
	Use:     "start",
	Short:   "start vblog-api server",
	Long:    "启动服务",
	Example: "vblog-api start -f etc/config.toml",
	Run: func(cmd *cobra.Command, args []string) {
		// 加载配置
		switch configType {
		case "file":
			cmd.Println("load config from:", filePath)
			err := conf.LoadConfigFromToml(filePath)
			cobra.CheckErr(err)
		case "env":
			cmd.Println("load config from env")
			err := conf.LoadConfigFromEnv()
			cobra.CheckErr(err)
		case "etcd":
			cmd.PrintErr("not implement")
			return
		default:
			cmd.PrintErr("unsupport config type, support [file,env,etcd]")
			return
		}

		// 初始化app
		err := apps.InitApps()
		cobra.CheckErr(err)

		// 创建http服务
		server := gin.Default()

		// 开启跨域中间件
		cm := cors.New(cors.Config{
			AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
			AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
			AllowCredentials: true,
			MaxAge:           12 * time.Hour,
			AllowAllOrigins:  true,
		})
		server.Use(cm)

		// 初始化所有http实例类
		v1 := server.Group("/vblog/api/v1")
		err = apps.InitHttp(v1)
		cobra.CheckErr(err)

		// 启动http
		if err := server.Run(":8050"); err != nil {
			fmt.Println(err)
		}
	},
}

func init() {
	Cmd.Flags().StringVarP(&configType, "config-type", "t", "file", "配置加载方式: [file,env,etcd]")
	Cmd.Flags().StringVarP(&filePath, "file-path", "f", "etc/config.toml", "配置文件路径")
}
